package com.panda.web.service.commons.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.panda.web.domain.vo.YjsEditionVO;
import com.panda.web.entity.commons.GraduateEdition;
import com.panda.web.entity.commons.GraduateEdition;
import com.panda.web.mapper.commons.GraduateEditionMapper;
import com.panda.web.mapper.commons.GraduateEditionMapper;
import com.panda.web.service.commons.IGraduateEditionService;
import com.panda.web.service.commons.IGraduateEditionService;
import com.panda.web.utils.pageutils.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.Collator;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 专业分类Service业务层处理
 *
 * @author cpanda
 * @date 2025-03-05
 */
@Slf4j
@Service
public class GraduateEditionServiceImpl extends ServiceImpl<GraduateEditionMapper, GraduateEdition> implements IGraduateEditionService {
    @Autowired
    GraduateEditionMapper editionMapper;

    /**
     * 分页查询
     *
     * @param dto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<GraduateEdition> PageList(GraduateEdition dto, Integer pageNum, Integer pageSize) {

        Page<GraduateEdition> page = new Page<>(pageNum, pageSize);
        QueryWrapper<GraduateEdition> queryWrapper = new QueryWrapper();//需要处理查询条件
        IPage<GraduateEdition> editionIPage = editionMapper.selectPage(page, queryWrapper);
        long total = editionIPage.getTotal();
        List<GraduateEdition> records = editionIPage.getRecords();

        return new PageResult<>(records, total, pageNum, pageSize);
    }

    /**
     * 无分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public List<GraduateEdition> choiceList(GraduateEdition dto) {
        QueryWrapper<GraduateEdition> queryWrapper = new QueryWrapper();//需要处理查询条件
        //构建查询条件
        List<GraduateEdition> editionList = editionMapper.selectList(queryWrapper);

        return editionList;
    }

    /**
     * 回显数据
     *
     * @param editionId
     * @return
     */
    @Override
    public GraduateEdition selectById(Long editionId) {
        GraduateEdition edition = editionMapper.selectById(editionId);
        return edition;
    }

    /**
     * 新增
     *
     * @param edition
     * @return
     */
    @Override
    public int insert(GraduateEdition edition) {
        editionMapper.insert(edition);
        return 1;
    }

    /**
     * 修改数据
     *
     * @param edition
     * @return
     */
    @Override
    public int updateEditionById(GraduateEdition edition) {

        editionMapper.updateById(edition);
        return 1;
    }

    /**
     * 删除数据(逻辑删除)
     *
     * @param ids
     * @return
     */
    @Override
    public int removeByEditionIds(List<Long> ids) {
        for (Long id : ids) {
            GraduateEdition edition = editionMapper.selectById(id);
            editionMapper.updateById(edition);
        }
        return 1;
    }

    /**
     * 树结构查询
     *
     * @param edition
     * @return
     */
    @Override
    public List<YjsEditionVO> getGraduateTree(GraduateEdition edition) {
        // 1. 查询所有数据

        List<GraduateEdition> allEditions = editionMapper.selectList(null);

        // 2. 构建树形结构
        List<YjsEditionVO> rootNodes = allEditions.stream()
                .filter(e -> {
                    // 判断 className 为 "学硕" 时父级为 1，为 "专硕" 时父级为 2
                    if (Objects.equals(edition.getClassName(),"学硕")||Objects.equals(edition.getClassName(),"学博")) {
                        return e.getParentId() == 1; // 学硕条件：父级为 1
                    } else if (Objects.equals(edition.getClassName(),"专硕")||Objects.equals(edition.getClassName(),"专博")) {
                        return e.getParentId() == 2; // 专硕条件：父级为 2
                    }
                    // 其他 className，默认筛选父级为 0 的一级节点
                    return e.getParentId() == 0;
                })
                .map(this::convertToVO)
                .sorted((a, b) -> Collator.getInstance(Locale.CHINA).compare(a.getName(), b.getName()))
                .collect(Collectors.toList());

        // 3. 递归构建树形结构
        for (YjsEditionVO rootNode : rootNodes) {
            buildTree(rootNode, allEditions);
        }

        // 4. 根据名称进行模糊搜索
        if (edition.getName() != null && !edition.getName().isEmpty()) {
            rootNodes = filterTreeByName(rootNodes, edition.getName());
        }


        return rootNodes;
    }

    private YjsEditionVO convertToVO(GraduateEdition edition) {
        YjsEditionVO vo = new YjsEditionVO();
        vo.setGraduateId(edition.getGraduateId());
        vo.setParentId(edition.getParentId());
        vo.setName(edition.getName());
        vo.setClassName(edition.getClassName());
        return vo;
    }

    //子节点
    private void buildTree(YjsEditionVO parentNode, List<GraduateEdition> allEditions) {
        List<YjsEditionVO> children = allEditions.stream()
                .filter(e -> e.getParentId().equals(parentNode.getGraduateId()))
                .map(this::convertToVO)
                .sorted((a, b) -> Collator.getInstance(Locale.CHINA).compare(a.getName(), b.getName()))
                .collect(Collectors.toList());

        if (!children.isEmpty()) {
            parentNode.setChildren(children);
            for (YjsEditionVO child : children) {
                buildTree(child, allEditions);
            }
        }
    }

    private List<YjsEditionVO> filterTreeByName(List<YjsEditionVO> nodes, String name) {
        List<YjsEditionVO> result = new ArrayList<>();
        if (nodes == null) {
            return result; // 如果 nodes 为 null，直接返回空列表
        }

        for (YjsEditionVO node : nodes) {
            // 检查当前节点是否匹配
            boolean isCurrentNodeMatch = node.getName() != null && node.getName().contains(name);

            // 递归检查子节点
            List<YjsEditionVO> filteredChildren = null;
            if (node.getChildren() != null) {
                filteredChildren = filterTreeByName(node.getChildren(), name);
            }

            // 如果当前节点匹配，或者子节点有匹配，则加入结果
            if (isCurrentNodeMatch || (filteredChildren != null && !filteredChildren.isEmpty())) {
                YjsEditionVO copyNode = new YjsEditionVO();
                copyNode.setGraduateId(node.getGraduateId());
                copyNode.setParentId(node.getParentId());
                copyNode.setName(node.getName());
                copyNode.setClassName(node.getClassName());

                // 如果当前节点匹配，返回所有子节点
                if (isCurrentNodeMatch) {
                    copyNode.setChildren(node.getChildren()); // 返回所有子节点
                } else if (filteredChildren != null && !filteredChildren.isEmpty()) {
                    // 如果子节点有匹配，设置过滤后的子节点
                    copyNode.setChildren(filteredChildren);
                }

                result.add(copyNode);
            }
        }
        return result;
    }


//    // 处理VO数据封装
//    private List<YjsEditionVO> YjsEditionVOToList(List<GraduateEdition> editionList) {
//        List<YjsEditionVO> voList = new ArrayList<>();
//        if (editionList.size() > 0 && !editionList.isEmpty()) {
//            for (GraduateEdition edition :editionList){
//                YjsEditionVO vo = new YjsEditionVO();
//                BeanUtils.copyProperties(edition, vo);
//                voList.add(vo);
//            }
//        }
//        return voList;
//    }


}